package com.hs.hsphonecabinet.ui

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.util.DisplayMetrics
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.facade.callback.NavigationCallback
import com.alibaba.android.arouter.launcher.ARouter
import com.hs.common.RouteIndex
import com.hs.framework.base.BaseDataBindActivity
import com.hs.framework.toast.TipsToast
import com.hs.framework.utils.FileUtils
import com.hs.framework.utils.MMKVUtil
import com.hs.framework.utils.PermissionUtil
import com.hs.framework.utils.StatusBarSettingHelper
import com.hs.mod_syslog.annotation.SysLogIntercept
import com.hs.hsphonecabinet.databinding.ActivitySplashBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


@Route(path = RouteIndex.splashActivity)
@AndroidEntryPoint
class SplashActivity : BaseDataBindActivity<ActivitySplashBinding>() {
    private val ROOTNAME: String = "db_hs_phone"


    override fun initView(savedInstanceState: Bundle?) {
        StatusBarSettingHelper.setStatusBarTranslucent(this)
        println("----ARouter---SplashActivity--------")
        ARouter.getInstance().inject(this)
//        val displayMetrics = DisplayMetrics()
////        // 获取窗口管理器服务
////        // 获取窗口管理器服务
//        this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics)
//        val widthPixels = displayMetrics.widthPixels
//        val heightPixels = displayMetrics.heightPixels
//        val density = displayMetrics.density
//        val densityDpi = displayMetrics.densityDpi
//        Log.d("ScreenResolution", "屏幕宽度（像素）: $widthPixels") // 1024
//        Log.d("ScreenResolution", "屏幕高度（像素）: $heightPixels")//  504
//        Log.d("ScreenResolution", "屏幕密度: $density") // 2.0
//        Log.d("ScreenResolution", "屏幕密度DPI: $densityDpi") // 320
        checkReadWritePermission();
    }

    //    "android.permission.MANAGE_EXTERNAL_STORAGE",
//    "android.permission.RECORD_AUDIO",
//    "android.permission.USB_PERMISSION"
    private val PERMISSION_REQUEST_CODE = 1001
    private val REQUEST_MANAGE_EXTERNAL_STORAGE = 1002
    private val permissionArray = arrayOf(
        "android.permission.WRITE_EXTERNAL_STORAGE",
        "android.permission.READ_EXTERNAL_STORAGE",
        "android.permission.CAMERA"
    )

    @SysLogIntercept("去主页")
    fun  test(i : Int ){

    }

    /**
     *  查看读写文件的权限
     */
    private fun checkReadWritePermission() {
        // 大于7  就申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermission();
        } else {
            TipsToast.showTips("不支持低于7.0的系统")
        }
    }

    /***
     *  请求所有权限
     */
    private fun requestPermission() {
        val bResult: Boolean = PermissionUtil.checkPermission(
            this,
            permissionArray,
            PERMISSION_REQUEST_CODE
        )
        // 全部给授权了
        if (bResult) {
            requestManageExternalStoragePermission()
        }
    }

    // android11 以上的权限申请
    private fun requestManageExternalStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
                startActivityForResult(
                    intent,
                    REQUEST_MANAGE_EXTERNAL_STORAGE
                )
            } else {
                // 已经有权限，可进行创建目录等后续操作
                gotoMainActivity()
            }
        } else {
            gotoMainActivity()
        }
    }

    // 申请权限的回调
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSION_REQUEST_CODE) {
            var allGranted = true
            for (result in grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false
                    break
                }
            }
            if (allGranted) {
                // 在这里可以继续后续操作，比如去申请更高级别的存储管理权限（如果需要操作根目录）
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    requestManageExternalStoragePermission()
                }
            } else {
                // 权限申请被拒绝，可以进行相应提示等处理
                Toast.makeText(this, "权限申请失败，请授予读写权限", Toast.LENGTH_SHORT).show()
            }
        } else if (requestCode == REQUEST_MANAGE_EXTERNAL_STORAGE) {
            val result = PermissionUtil.checkGrant(grantResults)
            if (result) {
                gotoMainActivity()
            } else {
                Toast.makeText(this, "权限申请失败，请授予读写权限", Toast.LENGTH_SHORT).show()
            }
        }
    }
    // 去主页

    private fun gotoMainActivity() {
            lifecycleScope.launch(Dispatchers.IO) {
                    // 创建一个新目录-根目录
                    val rootPath : String = FileUtils.createDbRootPath(ROOTNAME)
                    MMKVUtil.putString("ROOTPATH",rootPath)
                    withContext(Dispatchers.Main){
                    val mPostcard =  ARouter.getInstance().build(RouteIndex.mainActivity)
                    ARouter.getInstance().navigation(this@SplashActivity,mPostcard,1,object : NavigationCallback {

                        override fun onFound(postcard: Postcard) {
                            Log.d("ARouter", "找到了目标路由: ${postcard.path}")
                        }

                        override fun onLost(postcard: Postcard) {
                            Log.e("ARouter", "丢失目标路由: ${postcard.path}")
                        }

                        override fun onArrival(postcard: Postcard) {
                            Log.d("ARouter", "成功到达目标路由: ${postcard.path}")
                            test(158)
                            finish()
                        }

                        override fun onInterrupt(postcard: Postcard) {
                            Log.e("ARouter", "导航被中断: ${postcard.path}")
                        }

                    })
//                finish()

            }

        }

    }
}